package com.rtsapp.server.domain.utils;

import com.rtsapp.server.common.ByteBuffer;
import com.rtsapp.server.domain.IEntity;

/**
 * 操作次数记录类
 *
 */
public class NumOfOperation {


    private final IEntity entity;

    //操作次数
    protected int times;
    //最后曹组时间
    protected long lastOperationTime;

    public NumOfOperation( IEntity entity ) {
        this.entity = entity;
    }

    public NumOfOperation( IEntity entity, ByteBuffer buffer) {
        this.entity = entity;
        this.times = buffer.readInt();
        this.lastOperationTime = buffer.readLong();
    }

    public NumOfOperation( IEntity entity, int times, long lastOperationTime) {
        this.entity = entity;
        this.times = times;
        this.lastOperationTime = lastOperationTime;
    }

    public NumOfOperation( IEntity entity, String timesStr, String lastOperationTimeStr) {
        this.entity = entity;
        this.times = Integer.parseInt(timesStr);
        this.lastOperationTime = Long.valueOf(lastOperationTimeStr);
    }

    public NumOfOperation( IEntity entity,  String[] numOfOperationStrs) {
        this.entity = entity;
        this.times = Integer.parseInt(numOfOperationStrs[0]);
        this.lastOperationTime = Long.valueOf(numOfOperationStrs[1]);
    }

    public static NumOfOperation valueOf( IEntity entity,  String timesStr, String lastOperationTimeStr) {
        return new NumOfOperation( entity, timesStr, lastOperationTimeStr);
    }

    public static NumOfOperation valueOf( IEntity entity,  int times, long lastOperationTime) {
        return new NumOfOperation( entity, times, lastOperationTime);
    }

    public static NumOfOperation valueOf( IEntity entity,  String[] numOfOperationStrs) {
        return new NumOfOperation( entity, numOfOperationStrs);
    }

    public String toString() {
        return new StringBuffer().append(times).append(",").append(lastOperationTime).toString();
    }

    public void writeToByteBuffer(ByteBuffer buffer) {
        buffer.writeInt(times);
        buffer.writeLong(lastOperationTime);
    }


    /**
     * 返回最后记录的操作时间
     * @return
     */
    public long getLastOperationTime() {
        return lastOperationTime;
    }

    /**
     *
     * @return
     */
    public int checkAndGetTimes() {
        checkOperationTimesReset();
        return times;
    }

    /**
     * 增加操作次数1次
     * @return
     */
    public int timesPlus() {
        checkOperationTimesReset();
        lastOperationTime = System.currentTimeMillis();
        return ++times;
    }


    /**
     * 增加操作次数为指定次数
     * @param times
     * @return
     */
    public int timesPlus(int times) {
        checkOperationTimesReset();
        lastOperationTime = System.currentTimeMillis();
        return this.times += times;
    }

    protected boolean checkOperationTimesReset() {
        return false;
    }

}
